package cn.wolfcode.crm.shiro;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.service.IEmployeeService;
import cn.wolfcode.crm.service.IPermissionService;
import cn.wolfcode.crm.service.IRoleService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class EmployeeRealm extends AuthorizingRealm {

    private IEmployeeService employeeService;
    private IRoleService roleService;
    private IPermissionService permissionService;

    public void setEmployeeService(IEmployeeService employeeService) {
        this.employeeService = employeeService;
    }

    public void setPermissionService(IPermissionService permissionService) {
        this.permissionService = permissionService;
    }

    public void setRoleService(IRoleService roleService) {
        this.roleService = roleService;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        String username = upToken.getUsername();
        Employee employee = employeeService.queryByusername(username);
        if (employee != null) {
            return new SimpleAuthenticationInfo(employee, employee.getPassword(), ByteSource.Util.bytes(employee.getName()), this.getName());
        }
        return null;
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        获取当前用户
        Employee employee = (Employee) principals.getPrimaryPrincipal();
        if (employee.isAdmin()) {
            info.addRole("admin");
            info.addStringPermission("*:*");
            return info;
        }
//        根据i到查询角色
        List<String> roles = roleService.queryRolesByEmployeeId(employee.getId());
        List<String> expressions = permissionService.queryExpressionsByEmployeeId(employee.getId());
        info.addRoles(roles);
        info.addStringPermissions(expressions);
        return info;
    }

}
